﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InductBase;
using SharpBolt.Graphics.GraphicInstances;

namespace SharpBolt.Collision.CollisionSprite
{
    public class CollisionSpriteInstance
    {
        public class CollisionEventArgs : EventArgs
        {
            public CollisionEventArgs(CollShape shape, CollShape otherShape, CollisionSpriteInstance sprite, CollisionSpriteInstance otherSprite)
            {
                this.Shape = shape;
                this.OthersShape = otherShape;
                this.Sprite = sprite;
                this.OtherSprite = otherSprite;
            }

            public CollShape Shape;
            public CollShape OthersShape;
            public CollisionSpriteInstance Sprite;
            public CollisionSpriteInstance OtherSprite;
        }

        public EventHandler<CollisionEventArgs> Collided;

        public CollisionSpriteSource Source;
        public CollisionSpriteSource.Frame CurrentFrame;

        public Transformation Transformation
        {
            get
            {
                if (spriteInstance == null) return Transformation.Default;
                return spriteInstance.Transformation;
            }

            private set
            {

            }
        }

        SpriteInstance spriteInstance;

        public void Attach(SpriteInstance spriteInstance)
        {
            if (spriteInstance != null)
            {
                if(this.spriteInstance!=null)
                this.spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);    
              
                spriteInstance.FrameChanged += new EventHandler(spriteInstance_FrameChanged);
            }

            this.spriteInstance = spriteInstance;    
        }

        public void Detach(SpriteInstance spriteInstance = null)
        {
            if (spriteInstance == null)
            {
                this.spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);
            }
            else
            {
                spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);
            }
        }

        void spriteInstance_FrameChanged(object sender, EventArgs e)
        {
            CurrentFrame = 
                Source.
                Sequences[spriteInstance.CurrentSequenceIndex].
                Frames[spriteInstance.CurrentFrameIndex];
        }

        public CollisionSpriteInstance(CollisionSpriteSource source)
        {
            Source = source;                      
        }
    }
}
